<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
ini_set('max_execution_time', '0');
/*******************
 *** 速卖通接口订单数据（调用聚石塔内数据）
 **********/
class AliexpressTowerApi
{
	//private $reqUrl = 'http://qimen.api.taobao.com/router/qmtest?'; //奇门测试地址
	private $reqUrl = 'http://qimen.api.taobao.com/router/qm?'; //正式上线运行中地址
	public function __construct()
	{
		$this->CI =& get_instance();
		$this->db = $this->CI->load->database('default', TRUE);
		$this->CI->load->library('amazondata');
		$this->CI->load->model('Function_m','fun');
	}
	public function getOrderList(){
		//测试账号 Ali-costumebuy
		$sql = "SELECT * FROM d_shop WHERE platfromname = 'aliexpress' and agent_visit = 0 ";
		$rs = $this->db->query($sql)->result_array();
		if(count($rs)>0){
			//根据店铺进行请求
			foreach($rs as $k_shop=>$v_shop){
				//正式操作相关数据
				$begin_date = date("m/d/Y H:i:s",strtotime('-15 days')); //获取30天内订单
				$end_date   = date("m/d/Y 23:59:59"); //当前日期
				//参数数组
				$param1 = array();
				$param1['create_date_end'] = $end_date; //当前日期
				$param1['create_date_start'] = $begin_date;  //获取一月内订单
				$param1['order_status_list'] = array('WAIT_SELLER_SEND_GOODS','IN_CANCEL','RISK_CONTROL');
				$param1['page'] = 1;
				$param1['page_size'] = 1;
				$method = 'aliexpress.trade.findorderlistquery';
				$arr_other = array('id'=>$v_shop['seller_login_id'],'target_app_key'=>$v_shop['appkey']);
				$paramArr = $this->joinParamArr($param1,$v_shop['appkey'],$method,$arr_other);
				$sign = $this->createSign($paramArr,$v_shop['appsecret']);
				$strParam = $this->createStrParam($paramArr);
				$strParam .= 'sign='.$sign;
				$url = $this->reqUrl.$strParam; //调用地址
				$result = file_get_contents($url);
				$result = json_decode($result);
				//print_r($result);exit;
				if(isset($result->response->result->total_item)){
					$total_page = ceil($result->response->result->total_item / 50);
					//获取相关数据
					for ($page = 1; $page <= $total_page; $page++) {
						$this->updtmpOrderData($page,$begin_date,$end_date,$v_shop);
					}
				}else{
					if(isset($result->response)){
						print_r($result->response);
						//exit;
					}
				}

			}
		}
		echo "OK";exit;

	}
	//更新相关订单数据
	private function updtmpOrderData($page,$begin_date,$end_date,$v_shop){
		//参数数组
		$param1 = array();
		$param1['create_date_end'] = $end_date; //当前日期
		$param1['create_date_start'] = $begin_date;  //获取一月内订单
		$param1['order_status_list'] = array('WAIT_SELLER_SEND_GOODS','IN_CANCEL','RISK_CONTROL');
		$param1['page'] = $page;
		$param1['page_size']= 50; //每页显示50条数据

		$method = 'aliexpress.trade.findorderlistquery';
		$arr_other = array('id'=>$v_shop['seller_login_id'],'target_app_key'=>$v_shop['appkey']);
		$paramArr = $this->joinParamArr($param1,$v_shop['appkey'],$method,$arr_other);
		$sign = $this->createSign($paramArr,$v_shop['appsecret']);
		$strParam = $this->createStrParam($paramArr);
		$strParam .= 'sign='.$sign;
		$url = $this->reqUrl.$strParam; //调用地址
		$result = file_get_contents($url);
		//$result = json_decode($result,"",512,JSON_BIGINT_AS_STRING);
		$result = json_decode(preg_replace('/("\w+"):(-?\d+(.\d+)?)/', '\1:"\2"', $result),""); //替换上述
		//print_r($result);exit;
		if(isset($result->response->result->order_list)){
			$arr_orderlist = $result->response->result->order_list;
			if(count($arr_orderlist)>0){
				//订单循环
				foreach($arr_orderlist as $key=>$value){
					$value = (array)$value;
					if(false !==stripos($value['order_id'], "e")){
						$value['order_id'] = number_format($value['order_id'],0,'','');
					}
					//print_r($value);exit;
					//print_r($value['order_id']);exit;
					//判断客户是否有取消订单的情况
					$sql = "SELECT * FROM db_aliexpress_ordertmp_new WHERE order_id = '{$value['order_id']}' ";
					$rs = $this->db->query($sql)->row_array();
					if($rs){
						//如果已存在该状态，直接执行下个循环
						if($rs['order_status']=="WAIT_SELLER_SEND_GOODS"){
							//客户取消订单
							if($value['order_status']=="IN_CANCEL"){
								//临时表也更新一下
								$this->db->update('db_aliexpress_ordertmp_new',array('order_status'=>'IN_CANCEL')," id=".$rs['id']);
							}
						}
						continue;
					}
					//相关数据更新到数据库表中
					$this->db->trans_begin();
					try{
						//订单相关数据
						$arr_order = array();
						$arr_order['order_id'] = $value['order_id'];
						$arr_order['gmt_create'] = $value['gmt_create'];
						$arr_order['gmt_pay_time'] = $value['gmt_pay_time'];
						$arr_order['buyer_login_id'] = $value['buyer_login_id'];
						$arr_order['buyer_signer_fullname'] = addslashes($value['buyer_signer_fullname']);
						$arr_order['seller_signer_fullname'] = addslashes($value['seller_signer_fullname']);
						$arr_order['order_status'] = $value['order_status'];
						$arr_order['left_send_good_day'] = $value['left_send_good_day'];
						$arr_order['biz_type'] = $value['biz_type']; //订单类型
						$arr_order['fund_status'] = $value['fund_status']; //资金状态 PAY_SUCCESS:付款成功;
						$arr_order['frozen_status'] = $value['frozen_status'];
						$arr_order['currency_code'] = $value['pay_amount']->currency_code; //USD
						$arr_order['pay_amount'] = round($value['pay_amount']->cent/$value['pay_amount']->cent_factor,2); //按结算支付金额 包含运费
						$arr_order['postageservice'] = $value['product_list'][0]->logistics_service_name;
						$arr_order['payment_type'] = $value['payment_type'];
						//查询订单详情 包含地址信息，物流信息等
						//参数数组
						$param1 = array();
						$param1['order_id'] = $value['order_id']; //当前日期
						//print_r($arr_order);exit;
						$method = 'aliexpress.trade.findorderbyid';
						$arr_other = array('id'=>$v_shop['seller_login_id'],'target_app_key'=>$v_shop['appkey']);
						$paramArr = $this->joinParamArr($param1,$v_shop['appkey'],$method,$arr_other);
						$sign = $this->createSign($paramArr,$v_shop['appsecret']);
						$strParam = $this->createStrParam($paramArr);
						$strParam .= 'sign='.$sign;
						$url = $this->reqUrl.$strParam; //调用地址
						$order_detail = file_get_contents($url);
						//$order_detail = json_decode($order_detail,"",512,JSON_BIGINT_AS_STRING);
						$order_detail = json_decode(preg_replace('/("\w+"):(-?\d+(.\d+)?)/', '\1:"\2"', $order_detail),""); //替换上述
						//print_r($order_detail);exit;
						if(isset($order_detail->response->result)){
							$obj_order_detail = $order_detail->response->result;
							$arr_order['order_amount'] = $obj_order_detail->order_amount->amount; //包含运费
							//$arr_order['currency_code'] = $obj_order_detail->order_amount->currency_code;
							$arr_order['country'] = $obj_order_detail->receipt_address->country; //UK
							$arr_order['province'] = addslashes($obj_order_detail->receipt_address->province);
							$arr_order['city'] = addslashes($obj_order_detail->receipt_address->city);
							if($obj_order_detail->receipt_address->address2){
								$arr_order['address2'] = addslashes($obj_order_detail->receipt_address->address2);
							}
							$arr_order['detail_address'] = addslashes($obj_order_detail->receipt_address->detail_address);
							$arr_order['zip'] = addslashes($obj_order_detail->receipt_address->zip);
							if($obj_order_detail->receipt_address->phone_country){
								$arr_order['phone_country'] = addslashes($obj_order_detail->receipt_address->phone_country);
							}
							if($obj_order_detail->receipt_address->phone_area){
								$arr_order['phone_area'] = addslashes($obj_order_detail->receipt_address->phone_area);
							}
							if($obj_order_detail->receipt_address->phone_number){
								$arr_order['phone_number'] = addslashes($obj_order_detail->receipt_address->phone_number);
							}
							if($obj_order_detail->receipt_address->mobile_no){
								$arr_order['mobile_no'] = addslashes($obj_order_detail->receipt_address->mobile_no);
							}
							$arr_order['contact_person'] = addslashes($obj_order_detail->receipt_address->contact_person);
							$arr_order['seller_operator_login_id'] = $obj_order_detail->seller_operator_login_id; //cn1511042819

							//物流金额
							$arr_order['logistics_amount'] = $obj_order_detail->logistics_amount->amount;


							$arr_order['memo'] = $obj_order_detail->memo;

						}else{
							echo json_encode($order_detail);
							echo "<br/>";
							print_r($value);
							//exit;
						}

						//print_r($arr_order);exit;
						//echo "测试，目前还没有获取订单详情!";exit;
						$this->db->insert("db_aliexpress_ordertmp_new",$arr_order);
						$order_insert_id = $this->db->insert_id();
						//print_r($value['pay_amount']->currency_code);exit;

						//订单商品信息
						$arr_goods = array();
						$arr_goods_list = $value['product_list'];
						//print_r($arr_goods_list);exit;
						//商品数据
						foreach($arr_goods_list as $k=>$obj){
							$arr_goods['order_insert_id'] = $order_insert_id;
							$arr_goods['sku_code'] = $obj->sku_code;
							$arr_goods['order_id'] = $value['order_id']; //与订单id保持一致
							$arr_goods['product_count'] = $obj->product_count;
							$arr_goods['currency_code'] = $obj->total_product_amount->currency_code;
							$arr_goods['product_id'] = $obj->product_id;
							$arr_goods['amount'] = round($obj->total_product_amount->cent/$obj->total_product_amount->cent_factor,2); //商品总金额
							$arr_goods['product_snap_url'] = $obj->product_snap_url;
							$arr_goods['product_unit_price'] = round($obj->product_unit_price->cent/$obj->product_unit_price->cent_factor,2);
							$arr_goods['total_product_amount'] = round($obj->total_product_amount->cent/$obj->total_product_amount->cent_factor,2);
							$this->db->insert("db_aliexpress_ordertmpsell_new",$arr_goods); //更新商品表
						}

						$this->db->trans_commit(); //若执行成功，则提交
					}catch (Exception $e){
						$this->db->trans_rollback();
						//echo $e->getMessage();
					}

				}
			}
		}else{
			if(isset($result->error_response->msg)){
				echo $result->error_response->msg;
				echo "<br/>";
				print_r($v_shop);
				//exit;
			}
			echo "未知错误";exit;
		}

	}
	//插入 db_order_list 表相关数据
	public function insertOrderListData(){
		//获取国家相关中文名
		$arr_country = array();
		$sql_country = "SELECT countryid,countrynameen,countrynamecn FROM d_country ";
		$rs_country = $this->db->query($sql_country)->result_array();
		foreach($rs_country as $k=>$v){
			$arr_country[$v['countryid']] = $v['countrynamecn'];  // 这个对应英文名
			$arr_country[$v['countrynamecn']] = $v['countrynameen']; // 英文名对应中文名
		}
		//print_r($arr_country);exit;
		//获取相关货币跟人民币汇率列表
		$arr_rate = array();
		$sql_rate = "SELECT name,rate FROM d_moneyrate ";
		$rs_rate = $this->db->query($sql_rate)->result_array();
		foreach($rs_rate as $ka=>$va){
			$arr_rate[$va['name']] = $va['rate'];
		}
		$sql = "SELECT * FROM d_shop WHERE platfromname = 'aliexpress' and agent_visit=0   ORDER BY id DESC ";
		$rs = $this->db->query($sql)->result_array();
		foreach($rs as $k_shop=>$v_shop){
			$sql_ordertmp = "SELECT * FROM db_aliexpress_ordertmp_new WHERE  flag = 0 AND seller_operator_login_id = '{$v_shop['seller_login_id']}' GROUP BY order_id ";
			$rs_ordertmp = $this->db->query($sql_ordertmp)->result_array();
			if(count($rs_ordertmp)>0){
				//更新db_order_list
				foreach($rs_ordertmp as $k=>$v){
					$sql_order = "SELECT * FROM db_order_list WHERE tradeid = '{$v['order_id']}' ";
					$rs_order = $this->db->query($sql_order)->row_array();
					if($rs_order){
						$this->db->update("db_aliexpress_ordertmp_new",array("flag"=>1)," order_id = '".$v['order_id']."'");
						continue;
					}
					$arr_order_list['order_sn'] = $this->CI->amazondata->getNo('Aliexpress',$v['order_id']);//生成订单序号
					$arr_order_list['dates']  = date("Y-m-d"); //当天日期 判断order_sn使用
					$arr_order_list['ordertime']  = $v['gmt_create']; //订单日期时间
					$arr_order_list['order_source']  = "正常订单"; //默认
					$arr_order_list['customerid']  = $v['buyer_signer_fullname']; //客户id
					$arr_order_list['consignee']  =$v['contact_person']; //收货人

					$arr_order_list['country']  = $arr_country[$v['country']]; //国家英文名
					$arr_order_list['country_code']  = $v['country']; //国家二字编码
					$arr_order_list['country_cn']  = $arr_country[$arr_order_list['country']];
					$arr_order_list['province']  = $v['province'];
					$arr_order_list['city']  = $v['city'];
					if($v['address2']){
						$arr_order_list['address']  = $v['detail_address'];
						$arr_order_list['address2']  = $v['address2'];
					}else{
						$arr_order_list['address']  = $v['detail_address'];
						//$arr_order_list['address2']  = "";
					}
					$arr_order_list['zipcode']  = $v['zip'];
					if($v['phone_number']){
						$arr_order_list['tel']  = $v['phone_country'].$v['phone_area'].$v['phone_number'];
					}
					$arr_order_list['mobile']  = $v['mobile_no'];
					$arr_order_list['shopid']  = $v_shop['id']; //店铺id
					$arr_order_list['shopname']  = $v_shop['name'];
					$arr_order_list['shopoper']  = $v_shop['updateoper'];//店铺负责人

					$arr_order_list['platformID']  = $v_shop['platfrom'];//平台
					$exchange=$this->db->get_where("d_moneyrate","name='".$v["currency_code"]."'")->result_array();
					$arr_order_list['moneyrate']  = $exchange[0]["rate"];//汇率

					$arr_order_list['moneytype']  = $v['currency_code'];//货币类型
					$arr_order_list['tradeid']  = $v['order_id']; //交易单号

					//使用实际付款金额来计算
					$arr_order_list['goods_originask']  = $v['pay_amount']-$v['logistics_amount']; //付款金额减去运费 美元
					$arr_order_list['goods_amount']  = $arr_order_list['goods_originask']*$arr_order_list['moneyrate'];//人民币


					$arr_order_list['shipping_originask']  = $v['logistics_amount']; //原始快递费
					$arr_order_list['shipping_fee']  = $v['logistics_amount']*$arr_order_list['moneyrate']; //物流费 人民币
					if($v_shop["shop_platform_fee"]>0)
					{
						$shop_platform_fee  =$v_shop["shop_platform_fee"];
					}else{
						$shop_platform_fee = 0.15;
					}
					if($v_shop["shop_pay_fee"]>0)
					{
						$shop_pay_fee  =$v_shop["shop_pay_fee"];
					}else{
						$shop_pay_fee = 0.015;
					}
					$arr_order_list['pay_fee']  = $arr_order_list['goods_amount']*$shop_pay_fee; //支付费用
					$arr_order_list['platform_fee']  = $arr_order_list['goods_amount']*$shop_platform_fee; //平台费用
					$arr_order_list['add_time'] = time();
					if($v['orderweight']){
						$arr_order_list['orderweight']  = $v['orderweight'];
					}
					$arr_order_list['saleschannel']  = 'Aliexpress';
					$arr_order_list['order_status']  = 2; //已支付
					//物流相关信息
					if($v['postageservice']){
						$arr_order_list['postageservice']  = $v['postageservice']; //自选物流
					}
					//留言
					if($v['memo']){
						$arr_order_list['remark']  = $v['memo']; //备注
					}

					$this->db->trans_begin();	//事务开始

					$this->db->insert('db_order_list',$arr_order_list);
					$insert_id = $this->db->insert_id(); //也就是db_order_sell 中order_id
					//更新日志记录
					$imgdata="";
					$imgdata["goods_id"] = $insert_id;	//订单ID db_order_list
					$imgdata["updatetime"] = date("Y-m-d H:i:s");
					$imgdata["createUid"] = 0;
					$imgdata["types"] = 3;
					$imgdata["content"] = '速卖通接口自动新增订单,交易ID='.$v['order_id'];
					$imgdata["createUser"] ='auto';
					$this->db->insert('db_goods_log', $imgdata);

					$sql_ordersell = "SELECT * FROM db_aliexpress_ordertmpsell_new WHERE order_id = '{$v['order_id']}' ";
					$rs_ordersell = $this->db->query($sql_ordersell)->result_array();
					$flag = 0;
					$order_weight = 0;
					foreach($rs_ordersell as $key=>$value){
						if($value['sku_code']){
							$sql_s = "SELECT * FROM db_goods WHERE goods_sku = '".$value['sku_code']."' or cognatelist like '%,".$value['sku_code'].",%' ";
							$rs_s = $this->db->query($sql_s)->row_array();
							if(count($rs_s)>0){
								$goods_id = $rs_s['goods_id'];
								$arr_order_sell['costprice'] = $rs_s['g_costprice'];
								$arr_order_sell['originsku'] = $rs_s['goods_parent_sku'];//原始sku
								$arr_order_sell['goods_weight'] = $rs_s['g_weight']?$rs_s['g_weight']:400;//毛重
								$order_weight = $order_weight+$arr_order_sell['goods_weight']*$value['product_count'];
							}else{
								$flag = 1;
								$goods_id = 0;
							}
						}else{
							$flag = 1;
							$goods_id = 0;
						}

						$arr_order_sell['order_id'] = $insert_id;
						$arr_order_sell['goods_id'] = $goods_id;
						if($rs_s['goods_name']){
							$arr_order_sell['goods_name'] = $rs_s['goods_name'];
						}
						if($value['sku_code']){
							$arr_order_sell['goods_sn'] = $value['sku_code'];
						}
						$arr_order_sell['goods_number'] = $value['product_count']; //商品数量
						$arr_order_sell['originsellprice'] = $value['total_product_amount'];
						$arr_order_sell['goods_price'] = $value['product_unit_price']*$arr_order_list['moneyrate'];
						$arr_order_sell['goods_amount'] = $value['total_product_amount']*$arr_order_list['moneyrate'];
						if($value['product_snap_url']){
							$arr_order_sell['product_link'] = $value['product_snap_url'];//毛重
						}
						$arr_order_sell["productId"]=$value["product_id"];
						if($value['memo']){
							$arr_order_sell['sale_remark'] = $value['memo'];//留言
						}
						$this->db->insert('db_order_sell',$arr_order_sell);
						$insert_sell_id = $this->db->insert_id(); //也就是db_order_sell 中order_id

					}
					if($flag){
						$this->db->where('order_id',$insert_id);
						$data['order_status'] = 7;
						$this->db->update('db_order_list',$data);
					}else{
						$this->db->update('db_order_list',array('orderweight'=>$order_weight)," order_id = '".$insert_id."'");
					}
					//更新flag状态
					$this->db->where('id',$v['id']);
					$d['flag'] = 1;
					$this->db->update('db_aliexpress_ordertmp_new',$d);
					//var_dump($this->db->last_query());exit;
					//若执行成功，则提交

					if ($this->db->trans_status() === FALSE)
					{
						$this->db->trans_rollback();
					}
					else
					{
						$this->db->trans_commit();
					}


				}

			}

		}
	}
	//更新相关运单号到店铺
	public function updShippingNumberOrderOnline(){
		$order_id = $this->CI->input->get('order_id'); //如果传入单个参数话,就只行该单个参数，否则执行相关循环
		//$order_id = "263887"; //测试
		//print_r($order_id);exit;
		//店铺相关操作
		$fileds = " id,appkey,appsecret,refresh_token,refresh_timeout,access_token,access_timeout,seller_login_id ";
		$sql_shop = "SELECT $fileds FROM d_shop WHERE platfromname = 'aliexpress' AND agent_visit = 0 ORDER BY id DESC ";
		$rs_shop = $this->db->query($sql_shop)->result_array();
		$shop_where = " (";
		$arr_shop = array();
		if(count($rs_shop)>0){
			foreach($rs_shop as $k_shop=>$v_shop){
				$shop_where.= $v_shop['id'].",";
				$arr_shop[$v_shop['id']] = $v_shop;
			}
			$shop_where = trim($shop_where,",");
			$shop_where.=")";
		}else{
			exit("店铺不存在!");
		}
		//获取所有订单列表
		$where = " WHERE (order_status = 4 or order_status = 5) AND is_update_platform = 0 "; //4为已发货状态 is_update_platform为未与线上同步
		$where .= " AND shipping_name is not null AND shipping_number is not null ";
		if($order_id){
			$where.=" AND order_id = '{$order_id}' ";
		}
		$where.= " AND shopid in $shop_where ";
		$where.= " AND order_source in('正常订单','手工创建','拆分订单','合并订单') ";
		//$where.=" limit 0,100 "; //可以限定执行一次获取多少条数据
		$sql_mabangorder = "SELECT order_id,shipping_name,shopid,tradeid,shipping_number FROM db_order_list ".$where;
		$rs_mabangorder = $this->db->query($sql_mabangorder)->result_array();
		//echo $sql_mabangorder;exit;
		if(count($rs_mabangorder)>0){
			//获取相关字段信息，然后创建线上订单
			$time=time(); //当前时间
			foreach($rs_mabangorder as $k=>$v){
				if(!$v['shipping_name']){
					continue;
				}
				if(!$v['shipping_number']){
					continue;
				}
				//验证授权以及数字签名来创建订单
				$arr_app_check = $arr_shop[$v['shopid']];
				$appKey = $arr_app_check['appkey'];
				$appScret = $arr_app_check['appsecret'];
				$seller_login_id = $arr_app_check['seller_login_id'];
				//拼接api签名相关参数 填写发货通知
				if($v['shipping_name']=="中邮上海挂号小包"){
					$v['shipping_name'] = "中邮小包挂";
				}
				//查询物流key
				$sql_key = "SELECT * FROM db_order_express WHERE name = '{$v['shipping_name']}' ";
				$rs_key = $this->db->query($sql_key)->row_array();

				//测试 固定参数
				//$v['tradeid'] = "91466987787138";
				//$v['shipping_number'] = "LZ276287074CN";
				//$rs_key['aliexpress_express']="EMS_ZX_ZX_US";
				//$appKey = '24853976';
				//$seller_login_id = 'cn1002294534';
				//$appScret = '802a5bb2c3b98c46a6cf1a11243f629d';

				//参数数组
				$param1 = array();
				$param1['service_name'] = $rs_key['aliexpress_express'];
				$param1['logistics_no'] = $v['shipping_number'];  //运单号
				$param1['send_type'] = "all"; //发货类型 默认全部发货
				$param1['out_ref'] = $v['tradeid']; //交易订单号;
				//$param1['id'] = $seller_login_id; //卖家登录id
				//声明发货接口
				$method = 'aliexpress.logistics.sellershipmentfortop';
				$arr_other = array('id'=>$seller_login_id,'target_app_key'=>$appKey,'logistics_no'=>$param1['logistics_no'],'send_type'=>'all','out_ref'=>$v['tradeid'],'service_name'=>$rs_key['aliexpress_express']);
				$paramArr = $this->joinParamArr($param1,$appKey,$method,$arr_other);
				$sign = $this->createSign($paramArr,$appScret);
				$strParam = $this->createStrParam($paramArr);
				$strParam .= 'sign='.$sign;
				$url = $this->reqUrl.$strParam; //调用地址
				$result = file_get_contents($url);
				$result = json_decode($result,true); //获取返回值
				//print_r($result);exit;
				if($result['response']['result_error_code']=="-1"){ //成功
					$this->db->where('order_id',$v['order_id']);
					$arr_plat['is_update_platform']=1;
					$this->db->update('db_order_list',$arr_plat); //说明已经同步过

					//更新日志表db_goods_log
					$imgdata["goods_id"] = $v['order_id'];	//订单ID db_order_list
					$imgdata["updatetime"] = date("Y-m-d H:i:s");
					$imgdata["createUid"] = 0;
					$imgdata["types"] = 3;
					$imgdata["content"] = '速卖通接口线上店铺已发货,交易ID='.$v['tradeid'].",运单号=".$v["shipping_number"];
					$imgdata["createUser"] ='auto';
					$this->db->insert('db_goods_log', $imgdata);

					//另一张日志表，记录与线上操作发货是否同步 db_onlineshop_log
					$onlinedata["orderId"] = $v['order_id'];	//订单ID db_order_list
					$onlinedata["updateTime"] = date("Y-m-d H:i:s");
					$onlinedata["shippingNumber"] =$v["shipping_number"];
					$onlinedata["shippingName"] =$v["shipping_name"];
					$onlinedata["types"] = "速卖通同步线上发货操作"; //同步发货操作
					$onlinedata["content"] = '速卖通接口发货操作同步,交易ID='.$v['tradeid'].",运单号=".$v["shipping_number"];
					//$onlinedata["errorMessage"] = ;//成功则不填写
					$this->db->insert('db_onlineshop_log', $onlinedata);
				}else{
					if($result['response']['result_error_code']=="-2001"){
						$this->db->where('order_id',$v['order_id']);
						$arr_plat['is_update_platform']=1;
						$this->db->update('db_order_list',$arr_plat); //说明已经同步过

						//更新日志表db_goods_log
						$imgdata["goods_id"] = $v['order_id'];	//订单ID db_order_list 就是tradeid
						$imgdata["updatetime"] = date("Y-m-d H:i:s");
						$imgdata["createUid"] = 0;
						$imgdata["types"] = 3;
						$imgdata["content"] = '速卖通接口已发货,交易ID='.$v['order_id'].",运单号=".$v["shipping_number"];
						$imgdata["createUser"] ='auto';
						$this->db->insert('db_goods_log', $imgdata);
					}
					//另一张日志表，记录与线上操作发货是否同步 db_onlineshop_log
					if(isset($result['response']['result_error_desc'])){
						$onlinedata["orderId"] = $v['order_id'];	//订单ID db_order_list
						$onlinedata["updateTime"] = date("Y-m-d H:i:s");
						$onlinedata["shippingNumber"] =$v["shipping_number"];
						$onlinedata["shippingName"] =$v["shipping_name"];
						$onlinedata["types"] = "速卖通同步线上发货操作"; //同步发货操作
						$onlinedata["content"] = '速卖通接口发货操作同步,交易ID='.$v['tradeid'].",运单号=".$v["shipping_number"];
						$onlinedata["errorMessage"] = $result['error_message'];
						$this->db->insert('db_onlineshop_log', $onlinedata);
					}
				}
				//print_r($result);exit;
				// return $result['success']; //返回true
			}
		}else{
			exit("暂时无订单可创建!");
		}


	}
	private function joinParamArr($arr_param1,$appkey,$method,$arr_other=array()){
		$paramArr = array(
			'app_key' =>$appkey,
			'method' =>$method,
			'format' => 'json',
			'v' => '2.0',
			'sign_method'=>'md5',
			'timestamp' => date('Y-m-d H:i:s'),
			'param1' => json_encode($arr_param1)
		);
		if($arr_other){
			$paramArr = array_merge($paramArr,$arr_other);
		}
		return $paramArr;
	}
	//签名函数
	private function createSign ($paramArr,$appSecret) {
		$sign = $appSecret;
		ksort($paramArr);
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val != '') {
				$sign .= $key.$val;
			}
		}
		$sign.=$appSecret;
		$sign = strtoupper(md5($sign));
		return $sign;
	}
	//组参函数
	private function createStrParam ($paramArr) {
		$strParam = '';
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val != '') {
				$strParam .= $key.'='.urlencode($val).'&';
			}
		}
		return $strParam;
	}

	public function get_access_token(){
		$code = $this->input->get("code");
		$state = $this->input->get("state");
		//获取相关令牌并保存
		if($state=="b27f65c16048060867545e2efe312df8"){

			$url = 'https://oauth.aliexpress.com/token';
			$postfields= array('grant_type'=>'authorization_code',
				'client_id'=>$this->appkey,
				'client_secret'=>$this->secretKey,
				'code'=>$code,
				'sp'=>'ae',
				'redirect_uri'=>'http://139.196.235.137/aliexpressapi/get_access_token'
			);
			$post_data = '';
			foreach($postfields as $key=>$value){
				$post_data .="$key=".urlencode($value)."&";
			}
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1));
			$output = curl_exec($ch);
			//$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			curl_close($ch);
			$arr_ret = (array)json_decode($output);
			$data = array();
			$data['access_token'] = $arr_ret['access_token'];
			$data['access_timeout'] = substr($arr_ret['expire_time'],0,10);
			$data['refresh_token'] = $arr_ret['refresh_token'];
			$data['refresh_timeout'] = $arr_ret['refresh_token_valid_time'];
			//print_r($arr_ret);
			/**
			Array ( [access_token] => 50002700c45tlFBowqtcCYJtHkSC0xDcjgqAm0wgnIwk1ixWHmNfpVr81132cdaa00w
			[refresh_token] => 50003700a45NIO8iArzpT9CyKwFKyiSukcchrCnv1HIhPl2Hy2a9xp5dn110f2f6fOv
			[w1_valid] => 1524534402452 [refresh_token_valid_time] => 1524448002452
			[w2_valid] => 1524534402452 [user_id] => 2060764787 [expire_time] => 1524534402452
			[r2_valid] => 1524534402452 [locale] => zh_CN [r1_valid] => 1524534402452
			[sp] => ae [user_nick] => cn1511042819 ) **/
		}else{
			echo "参数错误";exit;
		}

	}
	public function auth_url_aliexpress(){
		$arr_param = array(
			'response_type'=>'code',
			'client_id'=>$this->appkey,
			'redirect_uri'=>$this->urlApi,
			'sp'=>'ae',
			'view'=>'web',
			'state'=>'b27f65c16048060867545e2efe312df8'
		);
		$str_param = http_build_query($arr_param);
		$https = 'https://oauth.aliexpress.com/authorize?'.$str_param;
		header("Location:".$https);
	}


}